// HSS.Logging.Management.ServerDatabasePanel.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       ServerDatabasePanel.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/04/2010
// ----------------------------------------------------------------------------
namespace HSS.Logging.Management
{
	#region Using Directives
	using System;
	using System.ComponentModel;
	using System.Data.SqlClient;
	using System.Drawing;
	using System.Windows.Forms;
	using HSS.Forms;
	using HSS.Data;
	#endregion


	internal sealed class ServerDatabasePanel : WizardPanel
	{
		private bool _buildDropDown = true;
		private ComboBox cboDatabases;
		private Label _databaseLabel;
		private Label _descriptionLabel;
		private Label _note1Label;
		private Label _note2Label;
		private TextBox txtPassword;
		private Label _passwordLabel;
		private TextBox txtServer;
		private Label _serverLabel;
		private RadioButton rdoSQL;
		private TextBox txtUserName;
		private Label _userNameLabel;
		private RadioButton rdoWindows;
		private string DEFAULT_DATABASE;
		private TableLayoutPanel overarchingTableLayoutPanel;

		public ServerDatabasePanel()
		{
			this.InitializeComponent();
			this.UpdateFonts();
			base.Caption = HSS.Logging.Management.Resources.Server_Caption;
			this.DEFAULT_DATABASE = HSS.Logging.Management.Resources.default_database;
			if (!string.IsNullOrEmpty(InstallWizard.Server))
				this.txtServer.Text = InstallWizard.Server;
			this.cboDatabases.Items.Add(this.DEFAULT_DATABASE);
			this.cboDatabases.SelectedIndex = 0;
			if (!string.IsNullOrEmpty(InstallWizard.Database))
			{
				this.cboDatabases.Items.Add(InstallWizard.Database);
				int index = this.cboDatabases.Items.IndexOf(InstallWizard.Database);
				this.cboDatabases.SelectedIndex = index;
			}
			this.txtPassword.Text = InstallWizard.Pwd;
			this.txtUserName.Text = InstallWizard.User;
			this.rdoWindows.Checked = InstallWizard.Trusted;
			this.rdoSQL.Checked = !InstallWizard.Trusted;
		}

		private void BuildDatabaseList()
		{
			ComboBox.ObjectCollection items = this.cboDatabases.Items;
			SqlDataReader reader = null;
			SqlConnection connection = null;
			SqlCommand command = null;
			if (this._buildDropDown)
			{
				items.Clear();
				string connectionString = ConstructConnectionString(this.GetServerName(), this.txtUserName.Text, this.txtPassword.Text, this.rdoWindows.Checked);
				try
				{
					Cursor.Current = Cursors.WaitCursor;
					connection = new SqlConnection(connectionString);
					command = new SqlCommand(HSS.Logging.Management.Resources.sqlGetDbList, connection);
					try
					{
						connection.Open();
					}
					catch (Exception exception)
					{
						InstallWizard.ShowRTLSafeMessageBox(HSS.Logging.Management.Resources.List_db_name_failed + "\n" + exception.Message, HSS.Logging.Management.Resources.Connection_failed, MessageBoxButtons.OK, MessageBoxIcon.Hand);
						return;
					}
					try
					{
						reader = command.ExecuteReader();
						while (reader.Read())
						{
							items.Add(reader.GetString(0));
						}
					}
					catch (Exception exception2)
					{
						InstallWizard.ShowRTLSafeMessageBox(HSS.Logging.Management.Resources.List_db_name_failed + "\n" + exception2.Message, HSS.Logging.Management.Resources.Read_database_failed, MessageBoxButtons.OK, MessageBoxIcon.Hand);
						return;
					}
					this._buildDropDown = false;
				}
				finally
				{
					try
					{
						if (reader != null)
						{
							reader.Close();
						}
						if (connection != null)
						{
							connection.Close();
						}
					}
					catch
					{
					}
					Cursor.Current = Cursors.Default;
				}
			}
		}

		private static string ConstructConnectionString(string server, string user, string password, bool trusted)
		{
			string text = null;
			if (server == "localhost")
			{
				server = DatabaseInstaller.LOCAL_MACHINE;
			}
			text = text + "server=" + server;
			if (trusted)
			{
				return (text + ";Trusted_Connection=true;");
			}
			string text2 = text;
			return (text2 + ";UID=" + user + ";PWD=" + password + ";");
		}

		private string GetServerName()
		{
			string text = this.txtServer.Text;
			if (text == "(local)")
			{
				text = DatabaseInstaller.LOCAL_MACHINE;
			}
			return text;
		}

		private void InitializeComponent()
		{
			this._descriptionLabel = new System.Windows.Forms.Label();
			this._note1Label = new System.Windows.Forms.Label();
			this._note2Label = new System.Windows.Forms.Label();
			this._databaseLabel = new System.Windows.Forms.Label();
			this._serverLabel = new System.Windows.Forms.Label();
			this.txtServer = new System.Windows.Forms.TextBox();
			this.txtPassword = new System.Windows.Forms.TextBox();
			this.txtUserName = new System.Windows.Forms.TextBox();
			this._passwordLabel = new System.Windows.Forms.Label();
			this.cboDatabases = new System.Windows.Forms.ComboBox();
			this._userNameLabel = new System.Windows.Forms.Label();
			this.rdoWindows = new System.Windows.Forms.RadioButton();
			this.rdoSQL = new System.Windows.Forms.RadioButton();
			this.overarchingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
			this.overarchingTableLayoutPanel.SuspendLayout();
			this.SuspendLayout();
			// 
			// _descriptionLabel
			// 
			this._descriptionLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this._descriptionLabel.AutoSize = true;
			this.overarchingTableLayoutPanel.SetColumnSpan(this._descriptionLabel, 2);
			this._descriptionLabel.Location = new System.Drawing.Point(0, 0);
			this._descriptionLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 3);
			this._descriptionLabel.Name = "_descriptionLabel";
			this._descriptionLabel.Size = new System.Drawing.Size(537, 26);
			this._descriptionLabel.TabIndex = 0;
			this._descriptionLabel.Text = "Specify the SQL Server name, database name to create or remove, and the credentia" +
				"ls to use when connecting to the database.";
			// 
			// _note1Label
			// 
			this._note1Label.AutoSize = true;
			this._note1Label.Location = new System.Drawing.Point(0, 32);
			this._note1Label.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
			this._note1Label.Name = "_note1Label";
			this._note1Label.Size = new System.Drawing.Size(33, 13);
			this._note1Label.TabIndex = 1;
			this._note1Label.Text = "Note:";
			// 
			// _note2Label
			// 
			this._note2Label.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
			this._note2Label.Location = new System.Drawing.Point(81, 29);
			this._note2Label.Name = "_note2Label";
			this._note2Label.Size = new System.Drawing.Size(460, 35);
			this._note2Label.TabIndex = 2;
			this._note2Label.Text = "The credentials must identify a user account that has permissions to create or re" +
				"move a database.";
			// 
			// _databaseLabel
			// 
			this._databaseLabel.AutoSize = true;
			this._databaseLabel.Location = new System.Drawing.Point(0, 193);
			this._databaseLabel.Margin = new System.Windows.Forms.Padding(0, 7, 3, 0);
			this._databaseLabel.Name = "_databaseLabel";
			this._databaseLabel.Size = new System.Drawing.Size(56, 13);
			this._databaseLabel.TabIndex = 11;
			this._databaseLabel.Text = "&Database:";
			this._databaseLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// _serverLabel
			// 
			this._serverLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this._serverLabel.AutoSize = true;
			this._serverLabel.Location = new System.Drawing.Point(0, 69);
			this._serverLabel.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
			this._serverLabel.Name = "_serverLabel";
			this._serverLabel.Size = new System.Drawing.Size(41, 13);
			this._serverLabel.TabIndex = 3;
			this._serverLabel.Text = "&Server:";
			this._serverLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// txtServer
			// 
			this.txtServer.AccessibleName = "Server";
			this.txtServer.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this.txtServer.Location = new System.Drawing.Point(79, 67);
			this.txtServer.Margin = new System.Windows.Forms.Padding(1, 3, 3, 1);
			this.txtServer.Name = "txtServer";
			this.txtServer.Size = new System.Drawing.Size(260, 20);
			this.txtServer.TabIndex = 4;
			this.txtServer.TextChanged += new System.EventHandler(this.OnLoginInfoChanged);
			// 
			// txtPassword
			// 
			this.txtPassword.AccessibleName = "Password";
			this.txtPassword.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this.txtPassword.Enabled = false;
			this.txtPassword.Location = new System.Drawing.Point(81, 163);
			this.txtPassword.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3);
			this.txtPassword.Name = "txtPassword";
			this.txtPassword.PasswordChar = '*';
			this.txtPassword.Size = new System.Drawing.Size(232, 20);
			this.txtPassword.TabIndex = 10;
			this.txtPassword.TextChanged += new System.EventHandler(this.OnLoginInfoChanged);
			// 
			// txtUserName
			// 
			this.txtUserName.AccessibleName = "User name";
			this.txtUserName.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this.txtUserName.Enabled = false;
			this.txtUserName.Location = new System.Drawing.Point(81, 137);
			this.txtUserName.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3);
			this.txtUserName.Name = "txtUserName";
			this.txtUserName.Size = new System.Drawing.Size(232, 20);
			this.txtUserName.TabIndex = 8;
			this.txtUserName.TextChanged += new System.EventHandler(this.OnLoginInfoChanged);
			// 
			// _passwordLabel
			// 
			this._passwordLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this._passwordLabel.AutoSize = true;
			this._passwordLabel.Location = new System.Drawing.Point(14, 166);
			this._passwordLabel.Margin = new System.Windows.Forms.Padding(14, 3, 3, 3);
			this._passwordLabel.Name = "_passwordLabel";
			this._passwordLabel.Size = new System.Drawing.Size(56, 13);
			this._passwordLabel.TabIndex = 9;
			this._passwordLabel.Text = "P&assword:";
			this._passwordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// cboDatabases
			// 
			this.cboDatabases.AccessibleName = "Database";
			this.cboDatabases.DisplayMember = "Name";
			this.cboDatabases.DropDownWidth = 251;
			this.cboDatabases.FormattingEnabled = true;
			this.cboDatabases.Location = new System.Drawing.Point(81, 189);
			this.cboDatabases.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
			this.cboDatabases.Name = "cboDatabases";
			this.cboDatabases.Size = new System.Drawing.Size(260, 21);
			this.cboDatabases.TabIndex = 12;
			this.cboDatabases.ValueMember = "Name";
			this.cboDatabases.DropDown += new System.EventHandler(this.OnDatabaseComboDropDown);
			this.cboDatabases.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnDatabaseComboKeyPress);
			// 
			// _userNameLabel
			// 
			this._userNameLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this._userNameLabel.AutoSize = true;
			this._userNameLabel.Location = new System.Drawing.Point(14, 140);
			this._userNameLabel.Margin = new System.Windows.Forms.Padding(14, 3, 3, 3);
			this._userNameLabel.Name = "_userNameLabel";
			this._userNameLabel.Size = new System.Drawing.Size(61, 13);
			this._userNameLabel.TabIndex = 7;
			this._userNameLabel.Text = "&User name:";
			this._userNameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// rdoWindows
			// 
			this.rdoWindows.AccessibleName = "Windows authentication";
			this.rdoWindows.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this.rdoWindows.AutoSize = true;
			this.rdoWindows.Checked = true;
			this.overarchingTableLayoutPanel.SetColumnSpan(this.rdoWindows, 2);
			this.rdoWindows.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.rdoWindows.Location = new System.Drawing.Point(0, 91);
			this.rdoWindows.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
			this.rdoWindows.Name = "rdoWindows";
			this.rdoWindows.Size = new System.Drawing.Size(138, 17);
			this.rdoWindows.TabIndex = 5;
			this.rdoWindows.TabStop = true;
			this.rdoWindows.Text = "&Windows authentication";
			this.rdoWindows.CheckedChanged += new System.EventHandler(this.OnLoginMethodChanged);
			// 
			// rdoSQL
			// 
			this.rdoSQL.AccessibleName = "SQL authentication";
			this.rdoSQL.Anchor = System.Windows.Forms.AnchorStyles.Left;
			this.rdoSQL.AutoSize = true;
			this.overarchingTableLayoutPanel.SetColumnSpan(this.rdoSQL, 2);
			this.rdoSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.rdoSQL.Location = new System.Drawing.Point(0, 114);
			this.rdoSQL.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
			this.rdoSQL.Name = "rdoSQL";
			this.rdoSQL.Size = new System.Drawing.Size(149, 17);
			this.rdoSQL.TabIndex = 6;
			this.rdoSQL.Text = "S&QL Server authentication";
			this.rdoSQL.CheckedChanged += new System.EventHandler(this.OnLoginMethodChanged);
			// 
			// overarchingTableLayoutPanel
			// 
			this.overarchingTableLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.overarchingTableLayoutPanel.ColumnCount = 2;
			this.overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
			this.overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
			this.overarchingTableLayoutPanel.Controls.Add(this._descriptionLabel, 0, 0);
			this.overarchingTableLayoutPanel.Controls.Add(this._note1Label, 0, 1);
			this.overarchingTableLayoutPanel.Controls.Add(this._passwordLabel, 0, 6);
			this.overarchingTableLayoutPanel.Controls.Add(this._databaseLabel, 0, 7);
			this.overarchingTableLayoutPanel.Controls.Add(this._note2Label, 1, 1);
			this.overarchingTableLayoutPanel.Controls.Add(this.txtPassword, 1, 6);
			this.overarchingTableLayoutPanel.Controls.Add(this.cboDatabases, 1, 7);
			this.overarchingTableLayoutPanel.Controls.Add(this.rdoSQL, 0, 4);
			this.overarchingTableLayoutPanel.Controls.Add(this.txtUserName, 1, 5);
			this.overarchingTableLayoutPanel.Controls.Add(this._serverLabel, 0, 2);
			this.overarchingTableLayoutPanel.Controls.Add(this.txtServer, 1, 2);
			this.overarchingTableLayoutPanel.Controls.Add(this.rdoWindows, 0, 3);
			this.overarchingTableLayoutPanel.Controls.Add(this._userNameLabel, 0, 5);
			this.overarchingTableLayoutPanel.Location = new System.Drawing.Point(0, 0);
			this.overarchingTableLayoutPanel.Name = "overarchingTableLayoutPanel";
			this.overarchingTableLayoutPanel.RowCount = 9;
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.Size = new System.Drawing.Size(544, 274);
			this.overarchingTableLayoutPanel.TabIndex = 0;
			// 
			// ServerDatabasePanel
			// 
			this.Controls.Add(this.overarchingTableLayoutPanel);
			this.Name = "ServerDatabasePanel";
			this.overarchingTableLayoutPanel.ResumeLayout(false);
			this.overarchingTableLayoutPanel.PerformLayout();
			this.ResumeLayout(false);

		}

		private void OnDatabaseComboDropDown(object sender, EventArgs args)
		{
			this.BuildDatabaseList();
		}

		private void OnDatabaseComboKeyPress(object sender, KeyEventArgs e)
		{
			if (this._buildDropDown && ((e.KeyData == Keys.Down) || (e.KeyData == Keys.Up)))
			{
				this.BuildDatabaseList();
			}
		}

		protected override void OnFontChanged(EventArgs e)
		{
			base.OnFontChanged(e);
			this.UpdateFonts();
		}

		private void OnLoginInfoChanged(object sender, EventArgs e)
		{
			this._buildDropDown = true;
		}

		private void OnLoginMethodChanged(object sender, EventArgs e)
		{
			this._buildDropDown = true;
			if (this.rdoWindows.Checked)
			{
				this.txtPassword.Enabled = false;
				this.txtUserName.Enabled = false;
			}
			else
			{
				this.txtPassword.Enabled = true;
				this.txtUserName.Enabled = true;
			}
		}

		private void UpdateFonts()
		{
			Font font = new Font(this.Font, FontStyle.Bold);
			this._note1Label.Font = font;
		}

		public override bool OnNext()
		{

			// Validate user provided values
			if (!ValidateSettings())
				return false;

			DataAccessConnection dac = new DataAccessConnection();
			dac.DataSource = this.Server;
			dac.InitialCatalog = this.DatabaseName;
			dac.IntegratedSecurity = this.rdoWindows.Checked;
			if (!dac.IntegratedSecurity)
			{
				dac.UserID = this.UserName;
				dac.Password = this.Password;
			}

			#region Validate database connectivity
			using (DataAccess da = new DataAccess(dac.ConnectionString))
			{

				if (InstallWizard.Action == WizardAction.AddAllFeatures)
				{
					// Do not specify database name
					// If the database does not exist, even though
					// the connection is successful; will error
					// stating user cannot login to the requested
					// database (initial catalog)
					da.Connection.InitialCatalog = string.Empty;
					Cursor.Current = Cursors.WaitCursor;
					this.Enabled = false;
					string error;
					if (!da.IsConnectionValid(out error))
					{
						Cursor.Current = Cursors.Default;
						this.Enabled = true;
						MessageBox.Show(this, error, this.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return false;
					}
				}
				else
				{
					Cursor.Current = Cursors.WaitCursor;
					this.Enabled = false;
					string error;
					if (!da.IsConnectionValid(out error))
					{
						Cursor.Current = Cursors.Default;
						this.Enabled = true;
						MessageBox.Show(this, error, this.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return false;
					}
					if (!SqlServices.IsInstalled(da))
					{
						Cursor.Current = Cursors.Default;
						this.Enabled = true;
						MessageBox.Show(this, "HSS Log is not installed on this database. Please select another database.", this.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return false;
					}
				}
			}
			#endregion

			// Set validated connection information
			InstallWizard.Database = dac.InitialCatalog;
			InstallWizard.Server = dac.DataSource;
			InstallWizard.ConnectionString = dac.ConnectionString;

			this.Enabled = true;
			Cursor.Current = Cursors.Default;
			return true;

		}
		private bool ValidateSettings()
		{
			if (this.txtServer.TextLength < 2)
			{
				MessageBox.Show("Please enter the server information.");
				this.txtServer.Focus();
				return false;
			}

			if (this.rdoSQL.Checked)
			{
				if (this.txtPassword.TextLength < 2)
				{
					MessageBox.Show("Please enter a valid password.");
					this.txtPassword.Focus();
					return false;
				}

				if (this.txtUserName.TextLength < 2)
				{
					MessageBox.Show("Please enter a valid user name.");
					this.txtUserName.Focus();
					return false;
				}
			}

			if (InstallWizard.Action == WizardAction.RemoveAllFeatures)
			{
				if (null == this.cboDatabases.SelectedItem)
				{
					MessageBox.Show("You must specify a database to uninstall from.");
					this.cboDatabases.Focus();
					return false;
				}
			}

			return true;
		}


		#region Properties
		private string Server
		{
			get
			{
				string text = this.txtServer.Text.Trim();
				if (text == "(local)" || text == "localhost")
					text = DatabaseInstaller.LOCAL_MACHINE;
				return text;
			}
		}
		private string UserName
		{
			get
			{
				if (!this.rdoSQL.Checked)
					return string.Empty;
				return this.txtUserName.Text.Trim();
			}
		}
		private string Password
		{
			get
			{
				if (!this.rdoSQL.Checked)
					return string.Empty;
				return this.txtPassword.Text;
			}
		}
		private string DatabaseName
		{
			get
			{
				string dbName = this.cboDatabases.Text;
				if (dbName == this.DEFAULT_DATABASE)
					dbName = HSS.Logging.Management.Resources.hssDbName;
				return dbName;
			}
		}
		#endregion
	}
}